<?php

class Authentication
{
	private $sessionID;
	private $userID;
	private $trialUserName;
	private $trialPassword;
	
	public function isLoggedOn($userID,$sessionID)
	{
		if($userID=="-1" || $sessionID=="-1")return FALSE;
		
		$database=$GLOBALS['DATABASE']->Recopy();
		$timenow=new DateTime("now");
		$sql = "SELECT UserID, SessionID, Expires FROM Sessions WHERE SessionID=".$sessionID.
		" AND UserID=".$userID."AND Expires>".$timenow->format("Y-m-d H:i:s");
		$database->executeSQL($sql);
		if($database->getNumRows()>0)return TRUE;
		else return FALSE;		
	}
	
	public function tryLogon($UserName,$Password)
	{
//		echo "Try logon<br>\n";
		$database=$GLOBALS['DATABASE']->Recopy();
		$sql="SELECT SnapUserID,Password from SnapUsers where LongName='".$UserName."'";
		$database->executeSQL($sql);
		if($database->getNumRows()==0)return -1;
		$row=$database->getRow();
		if($row['Password']!=$Password)return -1;
		$Expires = strftime("%Y-%m-%d %H:%M:%S",time() + 14400); //24 hours
		$sql="INSERT INTO Sessions (Expires, Username, UserID) Values('".$Expires."','".$UserName."','".$row['SnapUserID']."')";
		$database->executeSQL($sql);
		$SessionID=-1;
		$sql="SELECT SessionID FROM Sessions WHERE Expires = '$Expires' AND Username = '$UserName'";
		$database->executeSQL($sql);
//		echo "Numrows=".$database->getNumRows()."\n";
		if($row=$database->getRow()) $SessionID = $row['SessionID'];
//		echo "session id = ".$SessionID."\n";
		return $SessionID;
	}
	
	public function getCurrentUserID()
	{
		$userID = -1;
		$database=$GLOBALS['DATABASE']->Recopy();
		$sql="SELECT SessionID, UserID FROM Sessions WHERE SessionID = '".$this->sessionID."'";
		$database->executeSQL($sql);
		if($row=$database->getRow()) $userID = $row['UserID'];
		echo "session id = ".$this->sessionID;
		echo "user id  = ".$userID."\n";
		return $userID;
		}
}
